package com.hut.oa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hut.oa.model.bean.CommentReply;
import com.hut.oa.model.bean.CommentThumbs;
import com.hut.oa.model.bean.Dept;
import com.hut.oa.model.bean.DiscussActive;
import com.hut.oa.model.bean.DiscussArea;
import com.hut.oa.model.bean.DiscussComment;
import com.hut.oa.model.bean.DiscussVote;
import com.hut.oa.model.bean.DiscussVoteSelectContent;
import com.hut.oa.model.bean.Status;
import com.hut.oa.model.bean.Type;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.discuss.CommentThumbsDao;
import com.hut.oa.model.dao.discuss.DiscussActiveDao;
import com.hut.oa.model.dao.discuss.DiscussCommentDao;
import com.hut.oa.model.dao.discuss.DiscussCommentReplyDao;
import com.hut.oa.model.dao.discuss.DiscussDao;
import com.hut.oa.model.dao.discuss.DiscussVoteDao;
import com.hut.oa.model.dao.discuss.DiscussVoteSelectContentDao;
import com.hut.oa.model.dao.system.StatusDao;
import com.hut.oa.model.dao.system.TypeDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.model.mapper.DiscussVoteContentMapper;
import com.hut.oa.service.DiscussService;

@Controller
@RequestMapping("/discuss")
public class DiscussController {
	Logger log=LoggerFactory.getLogger(getClass());
	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
	DiscussDao ddao;
	
	@Autowired
	DiscussActiveDao dadao;
	
	@Autowired
	DiscussCommentDao dcdao;
	
	@Autowired
	DiscussVoteDao dvdao;
	
	@Autowired
	DiscussVoteSelectContentDao dvscdao;
	
	@Autowired
	StatusDao sdao;
	
	@Autowired
	TypeDao tdao;
	
	@Autowired
	StatusDao stdao;
	
	@Autowired
	UserDao udao;
	
	@Autowired
	DiscussCommentReplyDao dcrdao;
	
	@Autowired
	CommentThumbsDao ctdao;
	
	@Autowired
	DiscussVoteContentMapper voteMapper;
	
	@Autowired
	DiscussService ds;
	
	//查看帖子列表
	@RequestMapping
	public String talk(Model model,@RequestParam(name="comment")Integer comment,@PageableDefault(value=10) Pageable pageable){
		if (comment==0) {
			if (pageable.getSort()==null) {
				pageable=new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(new Order(Direction.DESC, "newTime")));
			}
			Page<DiscussArea> announce=ddao.announceDiscussList(pageable);
			model.addAttribute("discuss", announce);
		}
		if(comment==1) {
			if (pageable.getSort()==null) {
				pageable=new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(new Order(Direction.DESC, "newTime")));
			}
			Page<DiscussArea> notice=ddao.noticeDiscussList(pageable);
			model.addAttribute("discuss", notice);
		}
		if (comment==2) {
			if (pageable.getSort()==null) {
				pageable=new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(new Order(Direction.DESC, "discuss.newTime")));
			}
			List<DiscussArea> list=new ArrayList<>();
			Page<DiscussVote> vote=dvdao.voteDiscussList(pageable);
			if (vote!=null) {
				for (DiscussVote discussVote : vote) {
					DiscussArea discuss=discussVote.getDiscuss();
					list.add(discuss);
				}
			}
			Page<DiscussArea> list1=new PageImpl<>(list);
			model.addAttribute("discuss", list1);
		}
		if (comment==3) {
			if (pageable.getSort()==null) {
				pageable=new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(new Order(Direction.DESC, "discuss.newTime")));
			}
			List<DiscussArea> list=new ArrayList<>();
			Page<DiscussActive> active=dadao.activeDiscussList(pageable);
			if (active!=null) {
				for (DiscussActive discussActive : active) {
					DiscussArea discuss=discussActive.getDiscuss();
					list.add(discuss);
				}
			}
			Page<DiscussArea> list1=new PageImpl<>(list);
			model.addAttribute("discuss", list1);
		}
		//帖子类型
		List<Type> type=tdao.allType();
		model.addAttribute("type", type);
		//背景状态的图标
		List<Status> sta=stdao.findByModule("discuss");
		model.addAttribute("status", sta);
		//排序方式
		Sort sort=pageable.getSort();
		String str="";
		if (sort.toString().contains(("newTime"))) {
			str="时间";
		}else{
			str="评论数";
		}
		model.addAttribute("str", str);
		return "discuss/discuss";
	}
	//查看讨论、公告贴
	@RequestMapping("/view")
	public String view(@RequestParam(name="id")Long id,Model model,@PageableDefault(value=10,sort="time",direction=Direction.DESC) Pageable pageable){
		DiscussArea discuss=ddao.findOne(id);
		model.addAttribute("discuss", discuss);
		Page<DiscussComment> comments=dcdao.discussList(discuss,pageable);
		model.addAttribute("comments", comments);
		//排序方式
		Sort sort=pageable.getSort();
		String str="";
		if (sort.toString().contains(("time"))) {
			str="时间";
		}else if(sort.toString().contains(("replyNum"))){
			str="回复数";
		}else{
			str="赞数";
		}
		model.addAttribute("str", str);
		return "discuss/discuss_view";
	}
	
	/**
	 * 查看投票帖
	 * @return
	 */
	@RequestMapping("/view/vote")
	public String viewVote(@RequestParam(name="id")Long id,Model model,HttpSession session,@PageableDefault(value=10,sort="time",direction=Direction.DESC) Pageable pageable){
		User me=(User) session.getAttribute("userinfo");
		DiscussArea discuss=ddao.findOne(id);
		model.addAttribute("discuss", discuss);
		//评论
		Page<DiscussComment> comments=dcdao.discussList(discuss,pageable);
		model.addAttribute("comments", comments);
		
		DiscussVote vote=dvdao.voteOne(discuss);
		model.addAttribute("vote", vote);
		//投票内容
		List<DiscussVoteSelectContent> contents=dvscdao.voteAll(dvdao.voteOne(discuss));
		for (DiscussVoteSelectContent content : contents) {
			List<User> users=voteMapper.findUserById(content.getId());
			content.setUsers(users);
		}
		//参与用户
		model.addAttribute("contents", contents);
		List<User> users=voteMapper.findAllUserById(vote.getId());
		model.addAttribute("users",users);
		Long count=voteMapper.countAllById(vote.getId());
		model.addAttribute("count", count);
		//判断本用户是否投票
		
		String voted="fail";
		for (User user : users) {
			if (me.getId()==user.getId()) {
				voted="success";
				break;
			}
		}
		List<DiscussVoteSelectContent> contentId=voteMapper.contentIdByUserId(me.getId());
		model.addAttribute("contentId", contentId);
		model.addAttribute("voted", voted);
		//排序方式
		Sort sort=pageable.getSort();
		String str="";
		if (sort.toString().contains(("time"))) {
			str="时间";
		}else if(sort.toString().contains(("replyNum"))){
			str="回复数";
		}else{
			str="赞数";
		}
		model.addAttribute("str", str);
		return "discuss/discuss_view_vote";
	}
	/**
	 * 投票
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/add/vote")
	@ResponseBody
	public void vote(HttpSession session,Long selectedid[]){
		User me=(User) session.getAttribute("userinfo");
		if (selectedid!=null&&selectedid.length!=0) {
			for (int i = 0; i < selectedid.length; i++) {
				voteMapper.intoContent(me.getId(), selectedid[i]);
			}
		}
	}
	//查看活动贴
	@RequestMapping("/view/active")
	public String viewActive(@RequestParam(name="id")Long id,Model model,@PageableDefault(value=10,sort="time",direction=Direction.DESC) Pageable pageable){
		DiscussArea discuss=ddao.findOne(id);
		model.addAttribute("discuss", discuss);
		DiscussActive active= dadao.activeOne(discuss);
		model.addAttribute("active", active);
		Page<DiscussComment> comments=dcdao.discussList(discuss,pageable);
		model.addAttribute("comments", comments);
		Sort sort=pageable.getSort();
		String str="";
		if (sort.toString().contains(("time"))) {
			str="时间";
		}else if(sort.toString().contains(("replyNum"))){
			str="回复数";
		}else{
			str="赞数";
		}
		model.addAttribute("str", str);
		return "discuss/discuss_view";
	}
	
	@RequestMapping("/add")
	public String add(Model model){
		//帖子类型
		List<Type> type=tdao.allType();
		model.addAttribute("type", type);
		//背景状态
		List<Status> sta=stdao.findByModule("discuss");
		model.addAttribute("status", sta);
		return "discuss/discuss_add";
	}
	
	/**
	 * 增加讨论、公告帖子
	 * @param discuss
	 * @param session
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public void save(DiscussArea discuss,HttpSession session){
		System.out.println("================================"+discuss.getContent());
		User user=(User) session.getAttribute("userinfo");
		discuss.setUser(user);
		ddao.save(discuss.getDiscuss());
	}
	/**
	 * 增加投票帖子
	 * @param discuss
	 * @param session
	 */
	@RequestMapping(value="/save/vote",method=RequestMethod.POST)
	@ResponseBody
	public void saveVote(DiscussVote vote){
		for (DiscussVoteSelectContent voteContent : vote.getVoteContents()) {
			voteContent.setVote(vote);
		}
		dvdao.save(vote);
		
	}
	
	/**
	 * 增加活动帖子
	 * @param discuss
	 * @param session
	 */
	
	@RequestMapping(value="/save/active",method=RequestMethod.POST)
	@ResponseBody
	public void saveActive(DiscussActive active){
		dadao.save(active);
		
	}
	/**
	 * 增加评论帖
	 * @param comments
	 */
	@RequestMapping(value="/comment",method=RequestMethod.POST)
	@ResponseBody
	public void saveComment(DiscussComment comment){
		ds.updateCommentNum(comment);
	}
	
	/**
	 * 增加
	 *回复帖
	 * @param comments
	 */
	@RequestMapping(value="/reply",method=RequestMethod.POST)
	@ResponseBody
	public void saveReply(String contentReply,@RequestParam(name="commentId")Long commentId,HttpSession session,CommentReply commentReply){
		User user=(User) session.getAttribute("userinfo");
		DiscussComment comment=dcdao.findOne(commentId);
		commentReply.setContent(contentReply);
		commentReply.setUser(user);
		commentReply.setComment(comment);
		ds.updatereplyNum(commentReply);
	}
	
	/**
	 * 点赞
	 * @param commentId
	 * @param session
	 * @param thumbs
	 */
	@RequestMapping(value="/thumb",method=RequestMethod.POST)
	@ResponseBody
	public void savethumb(@RequestParam(name="commentId")Long commentId,HttpSession session,CommentThumbs thumbs){
		User user=(User) session.getAttribute("userinfo");
		DiscussComment comment=dcdao.findOne(commentId);
		thumbs.setUser(user);
		thumbs.setComment(comment);
		ds.updatethumbNum(thumbs);
	}
	/**
	 * 关键字查询帖子列表
	 */
	@RequestMapping("/search")
	public String search(Model model,String key,@PageableDefault(value=10,sort="newTime",direction=Direction.DESC) Pageable pageable){
		Page<DiscussArea> page;
		if(key!=null && key!=""){
			page=ddao.findByTitle(key, pageable);
		}else{
			page=ddao.findAll(pageable);
		}
		model.addAttribute("discuss", page);
		//状态的图标
		List<Status> sta=stdao.findByModule("discuss");
		model.addAttribute("status", sta);
		//排序方式
		Sort sort=pageable.getSort();
		String str="";
		if (sort.toString().contains(("newTime"))) {
			str="时间";
		}else{
			str="评论数";
		}
		model.addAttribute("str", str);
		return "discuss/discuss_search";
	}
	//删除帖子
	@RequestMapping(value="/delete",method=RequestMethod.GET)
	@ResponseBody
	public void delete(@RequestParam(name="discussId")Long discussId){
		DiscussArea discuss=ddao.findOne(discussId);
		if (discuss.getType()==0||discuss.getType()==1) {
			ddao.delete(discuss);
		}else if (discuss.getType()==3) {
			dadao.delete(dadao.activeOne(discuss));
		}else if(discuss.getType()==2){
			DiscussVote vote=dvdao.voteOne(discuss);
			List<DiscussVoteSelectContent> contents=dvscdao.voteAll(vote);
			for (DiscussVoteSelectContent discussVoteSelectContent : contents) {
				dvscdao.delete(discussVoteSelectContent);
			}
			dvdao.delete(vote);
		}
		
	}
	
	
}
